package service

import (
	"gin-mi/config"
	"gin-mi/pkg"
	"math/rand"
	"net/http"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

func SendSms(c *gin.Context) {
	var req struct {
		Mobile string `form:"mobile"`
	}
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err})
	}
	code := rand.Intn(900000) + 100000
	_, err := pkg.SendSms(req.Mobile, strconv.Itoa(code))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "发送失败"})
		return
	}
	err = config.Rdb.Set(c, "sms"+req.Mobile, code, time.Minute*3).Err()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "存储验证码失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  "发送成功",
	})
}
